package com.abe.test.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class UriToFile {

    public static File convertUriToImageFile(Context context, Uri fileUri, String fileName) {
        return convertUriToFile(context, fileUri, Environment.DIRECTORY_PICTURES, fileName);
    }

    public static File convertUriToVideoFile(Context context, Uri fileUri, String fileName) {
        return convertUriToFile(context, fileUri, Environment.DIRECTORY_MOVIES, fileName);
    }

    public static File convertUriToFile(Context context, Uri fileUri, String fileName) {
        if (isImage(context, fileUri)) {
            return convertUriToImageFile(context, fileUri, fileName);
        }
        if (isVideo(context, fileUri)) {
            return convertUriToVideoFile(context, fileUri, fileName);
        }
        return convertUriToFile(context, fileUri, null, fileName);
    }

    public static boolean isImage(Context context, Uri uri) {
        String mimeType = context.getContentResolver().getType(uri);
        return mimeType != null && mimeType.startsWith("image/");
    }

    public static boolean isVideo(Context context, Uri uri) {
        String mimeType = context.getContentResolver().getType(uri);
        return mimeType != null && mimeType.startsWith("video/");
    }

    public static File convertUriToFile(Context context, Uri fileUri, String type, String fileName) {
        ContentResolver contentResolver = context.getContentResolver();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        File file = null;
        try {
            inputStream = contentResolver.openInputStream(fileUri);
            file = new File(context.getExternalFilesDir(type), fileName); // 指定文件路径和名称
            outputStream = new FileOutputStream(file);

            byte[] buffer = new byte[1024 * 1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }
}